# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

# import json
# import codecs
# from tutorial.items import VideoItem, HouseItem


# class TutorialPipeline(object):
#     def __init__(self):
#         pass

#     def process_item(self, item, spider):
#         if isinstance(item, VideoItem):
#             self.file = codecs.open('video.json', 'a+', encoding='utf-8')
#         elif isinstance(item, HouseItem):
#             self.file = codecs.open('house.json', 'a+', encoding='utf-8')
#         else:
#             pass
#         line = json.dumps(dict(item), ensure_ascii=False) + "\n"
#         self.file.write(line)
#         return item

#     def spider_closed(self, spider):
#         self.file.close()

from scrapy import signals
from scrapy.exporters import JsonLinesItemExporter


class JsonExportPipeline(object):

    def __init__(self):
        self.files = {}

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls()
        crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
        crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def spider_opened(self, spider):
        file = open('%s_products.json' % spider.name, 'w+b')
        self.files[spider] = file
        self.exporter = JsonLinesItemExporter(file, ensure_ascii=False)
        self.exporter.start_exporting()

    def spider_closed(self, spider):
        self.exporter.finish_exporting()
        file = self.files.pop(spider)
        file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

# class VideoPipeline(object):
#     def __init__(self):
#         self.file = codecs.open('video.json', 'w', encoding='utf-8')

#     def process_item(self, item, spider):
#         if spider.name is not "video":
#             return item
#         line = json.dumps(dict(item), ensure_ascii=False) + "\n"
#         self.file.write(line)
#         return item

#     def spider_closed(self, spider):
#         self.file.close()


# class HousePipeline(object):
#     def __init__(self):
#         self.file = codecs.open('house.json', 'w', encoding='utf-8')

#     def process_item(self, item, spider):
#         line = json.dumps(dict(item), ensure_ascii=False) + "\n"
#         self.file.write(line)
#         return item

#     def spider_closed(self, spider):
#         self.file.close()
